<template>
  <div>
    <h1>抽奖记录表</h1>
  </div>
  <div>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="活动名称" prop="activeName">
        <el-input v-model="ruleForm.activeName" />
      </el-form-item>
      <el-form-item label="活动时间">
        <el-date-picker
          v-model="ruleForm.activeTime"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="截止时间"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="YYYY/MM/DD ddd"
          time-format="A hh:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="参与用户">
        <el-radio-group v-model="ruleForm.userFlag">
          <el-radio :value="0">部分</el-radio>
          <el-radio :value="1">全部</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="活动免费抽奖次数">
        <el-input-number
          v-model="ruleForm.freeTimes"
          :min="1"
          :max="10"
          @change="handleChange"
        />
      </el-form-item>

      <!-- 规则表 -->
      <el-form-item label="规则">
        <el-table :data="ruleData" stripe style="width: 100%">
          <el-table-column prop="ruleId" label="序号" />
          <el-table-column prop="ruleImage" label="图片">
            <template #default="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.ruleImage"
              />
            </template>
          </el-table-column>
          <el-table-column prop="ruleName" label="名称" />
          <el-table-column prop="winProd" label="奖品" />
          <el-table-column prop="winImage" label="中奖弹窗图片">
            <template #default="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.winImage"
              />
            </template>
          </el-table-column>
          <el-table-column prop="prodNum" label="数量" />
          <el-table-column prop="winChance" label="奖品概率" />
          <el-table-column label="操作"></el-table-column>
        </el-table>
        <div>
          <el-button type="primary" plain @click="onAddRule()">
            添加规则
          </el-button>
        </div>
      </el-form-item>

      <!-- 添加活动规则 -->

      <el-form-item label="中奖名单">
        <el-switch
          v-model="ruleForm.winFlag"
          size="large"
          active-text="开启"
          inactive-text="禁用"
          :active-value="0"
          :inactive-value="1"
        />
      </el-form-item>

      <el-form-item label="中奖记录">
        <el-switch
          v-model="ruleForm.winRecord"
          size="large"
          active-text="开启"
          inactive-text="禁用"
          :active-value="0"
          :inactive-value="1"
        />
      </el-form-item>

      <el-form-item label="活动状态">
        <el-switch
          v-model="ruleForm.activeStatus"
          size="large"
          active-text="开启"
          inactive-text="禁用"
          :active-value="0"
          :inactive-value="1"
        />
      </el-form-item>

      <el-form-item label="活动规则" style="width: 550px">
        <MyEditor v-model="ruleForm.activeContent"></MyEditor>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          添加
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 添加活动规则 -->
  <div>
    <el-dialog v-model="dialogFormVisible" title="规则添加" width="500">
      <el-form :model="form">
        <el-form-item label="活动名称" :label-width="formLabelWidth">
          <el-input v-model="form.ruleName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="活动图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/user/type/uploadTypeImage"
            :show-file-list="false"
            :headers="headers"
            :on-success="handleAvatarSuccess1"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="奖品" :label-width="formLabelWidth">
          <el-input v-model="form.winProd" autocomplete="off" />
        </el-form-item>
        <el-form-item label="中奖弹窗图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/team/index/uploadImage"
            :show-file-list="false"
            :headers="headers"
            :on-success="handleAvatarSuccess2"
          >
            <img v-if="imageUrlDialog" :src="imageUrlDialog" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="数量" :label-width="formLabelWidth">
          <el-input v-model="form.prodNum" autocomplete="off" />
        </el-form-item>
        <el-form-item label="奖品概率" :label-width="formLabelWidth">
          <el-input v-model="form.winChance" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onAddRuleSuccess()">
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { addActive } from "@/api/api";
import type { FormInstance, FormRules } from "element-plus";
//富文本
import MyEditor from "@/components/Editor/index.vue";
//上传图片
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

// 校验规则
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  activeContent: "",
  activeId: 0,
  activeName: "",
  activeStatus: 0,
  beginTime: "",
  createBy: "",
  createTime: "",
  endTime: "",
  freeTimes: 0,
  ruleList: [],
  updateBy: "",
  updateTime: "",
  userFlag: 0,
  winFlag: 0,
  winRecord: 0,
  activeTime: null,
});

const rules = ref<FormRules>({
  activeName: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
});

//数字输入框
const handleChange = (value: number | undefined) => {
  console.log(value);
};

//弹出框
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const onAddRule = () => {
  form.value = {
    prodNum: null,
    ruleImage: "",
    ruleName: "",
    winChance: null,
    winImage: "",
    winProd: "",
  };
  imageUrl.value = "";
  imageUrlDialog.value = "";
  dialogFormVisible.value = true;
};
// 规则表
const ruleData = ref<any>([]); //添加的是一个数组
const form = ref({
  prodNum: null,
  ruleImage: "",
  ruleName: "",
  winChance: null,
  winImage: "",
  winProd: "",
});

//上传图片
const headers = ref({
  token: window.sessionStorage.getItem("token") || "",
});
const imageUrl = ref("");
const imageUrlDialog = ref("");

const handleAvatarSuccess1: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  debugger;
  imageUrl.value = response.data;
};
const handleAvatarSuccess2: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrlDialog.value = response.data;
};

//保存活动规则
const onAddRuleSuccess = () => {
  const rule: any = {};
  //克隆一个对象
  Object.assign(rule, form.value);
  rule.ruleImage = imageUrl.value;
  rule.winImage = imageUrlDialog.value;
  ruleData.value.push(rule);
  dialogFormVisible.value = false;
};

//保存抽奖活动成功
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addActive(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          router.push("/home/ruleList");
        } else {
          ElMessage.error("添加失败");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
